//是否已经连接上ws
let isOpenSocket = false
//心跳间隔，单位毫秒
let heartBeatDelay = 5000
let heartBeatInterval = null
//心跳时发送的消息文本
let heartBeatText = {
	sendUser:"",
	receiveUser:"",
	isSystem:3,
	message:"ping"
}
//最大重连次数
let reconnectTimes = 5
let reconnectInterval = null
//重连间隔，单位毫秒
let reconnectDelay = 3000

let wsUrl = "ws://localhost:8081/chat/"

let socketTask = null

//这个参数是防止重连失败之后onClose方法会重复执行reconnect方法，导致重连定时器出问题
//连接并打开之后可重连，且只执行重连方法一次
let canReconnect = false

//封装的对象，最后以模块化向外暴露，
//init方法 初始化socketTask对象
//completeClose方法 完全将socketTask关闭（不重连）
//其他关于socketTask的方法与uniapp的socketTask api一致
let ws = {
	socketTask: null,
	init,
	send,
	completeClose
}

function init(userId) {
	socketTask = uni.connectSocket({
		url: wsUrl+userId,
		complete: (res)=> {
		}
	})
	socketTask.onOpen((res) => {
		clearInterval(heartBeatInterval)
		clearInterval(reconnectInterval)
		isOpenSocket = true
		canReconnect = true
		//开启心跳机制
		heartBeat()
	})
	//监听收到消息
	socketTask.onMessage((res) => {
		if(res.data != "当前用户不在线"){
			var str = JSON.parse(res.data) 
			if(str.isSystem != 3){ //3是心跳检测 
			console.log("wbjs收到了消息"+JSON.stringify(str))  
			//添加好友的系统信息 
				if(str.isSystem == 2){ 
					var add = uni.getStorageSync("addUser")
					if(typeof add == 'string' & add.length > 0){
						add = JSON.parse(add)
						add.push(str)
						uni.setStorageSync("addUser",JSON.stringify(add))
					}else{//首次添加
						var a = []
						a.push(str)
						uni.setStorageSync("addUser",JSON.stringify(a))
					}
					addtbbar()
					uni.$emit("system",str)
				} else if(str.isSystem == 1){//系统消息 
					var system = uni.getStorageSync("system")
					var user = JSON.parse(uni.getStorageSync('user'))
					if(str.message != user.id +"上线了"){
						if(typeof system == 'string' & system.length > 0){
						system = JSON.parse(system)
						system.push(str)
						uni.setStorageSync("system",JSON.stringify(system))
					}else{//缓存首次添加数据
						var a = []
						a.push(str)
						uni.setStorageSync("system",JSON.stringify(a))
					} 
					addtbbar()
					uni.$emit("system",str)
					}
				}else{//好友消息
					var message = uni.getStorageSync("message")
					if(typeof message == 'string' & message.length > 0){
						message = JSON.parse(message)
						message.push(str)
						uni.setStorageSync("message",JSON.stringify(message))
					}else{//首次添加
						var a = []
						a.push(str)
						uni.setStorageSync("message",JSON.stringify(a))
					}
					addtbbar()
					uni.$emit("system",str)
				}
				}
		}
	})
	socketTask.onError(()=>{
		this.$u.toast("重连中")
		reconnect()
	})
	socketTask.onClose(() => {
		if(isOpenSocket){
			console.log("ws与服务器断开")
		}else{
			console.log("连接失败")
		}
		isOpenSocket = false
		if(canReconnect){
			reconnect()
			canReconnect = false
		}
	})
	ws.socketTask = socketTask
}
//心跳检测
function heartBeat() {
	heartBeatInterval = setInterval(() => {
		send(JSON.stringify(heartBeatText));
	}, heartBeatDelay)
}
//发送消息
function send(value) {
	ws.socketTask.send({
		data: value,
		success() {
		},
		fail(){
			console.log("消息发送失败:"+value)
		}
	});
}
//重连
function reconnect() {
	//停止发送心跳
	clearInterval(heartBeatInterval)
	//如果不是人为关闭的话，进行重连
	if (!isOpenSocket) {
		let count = 0;
		reconnectInterval = setInterval(() => {
			uni.$u.toast("正在尝试重连")
			const user = JSON.parse(uni.getStorageSync('user'))
			init(user.id);
			count++
			//重连一定次数后就不再重连
			if(count >= reconnectTimes){
				clearInterval(reconnectInterval)
				uni.$u.toast("链接服务器失败")
			}
		}, reconnectDelay)
	}
}
//tabbar消息增加
function addtbbar() {
	var str = uni.getStorageSync("tabbar")
	var num = 0
	//首次的情况 
	console.log("str值:"+str) 
	if(typeof str == 'string' & str.length == 0 || parseInt(str) == 0){
		num = 1 
	}else{
		num = parseInt(uni.getStorageSync("tabbar"))
		num = ++num
	}
	console.log("wb里面的num是："+num)
	uni.setStorageSync("tabbar",JSON.stringify(num))
}
//关闭websoket
function completeClose(){
	//先将心跳与重连的定时器清除
	clearInterval(heartBeatInterval)
	clearInterval(reconnectInterval)
	canReconnect = false
	ws.socketTask.close()
	console.log("关闭了。。")
}

module.exports = ws
